import Vue from 'vue';
import store from '@/store';
import vueTheme from 'theme-vue';
import VueRouter from 'vue-router';
import adminRoute from './adminRoute';
import memberRoute from './memberRoute';
import staticRouter from './staticRouter';
import managerRoute from './managerRoute';
import principalRoute from './principalRoute';
import usercenterRoute from './usercenterRoute';
const VueRouterPush = VueRouter.prototype.push;
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterPush.call(this, location, onResolve, onReject)
	return VueRouterPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterReplace.call(this, location, onResolve, onReject)
	return VueRouterReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
const router = new VueRouter({
	routes: [
		...adminRoute,
		...memberRoute,
		...staticRouter,
		...managerRoute,
		...principalRoute,
		...usercenterRoute
	]
});
const whitelists = ['Login', 'Register', 'ForgetPass'];
const getRouterMenu = (arr, path) => {
	let obj = {};
	let menuData = [...arr, {
		path: '/usercenter'
	}, {
		path: '/announcement'
	}, {
		path: '/question'
	}, {
		path: 'commonQuestion'
	}];
	const findNode = (tree, callback) => {
		for (let i = 0; i < tree.length; i++) {
			if (path.indexOf(tree[i].path) !== -1) {
				callback(tree[i]);
				break;
			}
			if (tree[i]['children'] && tree[i]['children'].length > 0) {
				findNode(tree[i]['children'], callback)
			}
		}
	};
	findNode(menuData, data => {
		obj = {
			...data
		}
	})
	return Object.keys(obj).length === 0;
}
router.beforeEach((to, from, next) => {
	let Theme = new vueTheme();
	let token = Vue.prototype.$session.get('token');
	let siteInfo = store.getters.siteInfo;
	let userInfo = store.getters.userInfo;
	let menuData = store.getters.menuData || [];
	let isExistsMenu = getRouterMenu(menuData, to.path);
	let isLogin = !!token && !!userInfo;
	if (to.matched.some(n => n.name === 'Front')) {
		Theme.changeTheme('#600807');
	} else if (to.matched.some(n => n.name === 'Admin')) {
		Theme.changeTheme('#4361ee');
	} else if (to.matched.some(n => n.name === 'Member')) {
		Theme.changeTheme('#4361ee');
	}

	if (!to.matched.length) {
		next('/404');
		return false;
	}
	if (whitelists.indexOf(to.name) !== -1) {
		next();
		return false;
	} else if (!isLogin) {
		next('/login');
		return false;
	} else if (isExistsMenu) {
		/* if (menuData.some(n => n.path === '/index')) {
			next('/index');
			return false;
		} else {
			next(menuData[0].path);
			return false;
		} */
	} else {
		next();
		return false;
	}
	next();
})
export default router